package com.renwei.yunlong.activity.work;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.ImageFileAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.ReturnBean;
import com.renwei.yunlong.bean.UpdateUserIconBean;
import com.renwei.yunlong.event.SparePageRefreshEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.UploadManger;
import com.renwei.yunlong.view.SimpleOptionView;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;


/**
 * 审核--页面
 * <p>
 * Created by Administrator on 2017/8/29.
 */

public class SpareAuditActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, InvokeListener, TakePhoto.TakeResultListener, ImageFileAdapter.OnItemDeleteClickListener, AdapterView.OnItemClickListener {

    private static final String TAG = "SpareAuditActivity";
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.tv_spare)
    TextView tvSpare;
    @Bind(R.id.rl_spare)
    RelativeLayout rlSpare;
    @Bind(R.id.tv_input_title)
    TextView tvInputTitle;
    @Bind(R.id.et_input_content)
    EditText etInputContent;
    @Bind(R.id.tv_input_number)
    TextView tvInputNumber;
    @Bind(R.id.grid_view)
    GridView gridView;
    @Bind(R.id.button_through)
    Button buttonThrough;
    @Bind(R.id.button_not_through)
    Button buttonNotThrough;
    @Bind(R.id.button_cancel)
    Button buttonCancel;
    private String spareId;
    private String sprId;
    private String auditSay;
    private TakePhoto takePhoto;
    private PromptDialog promptDialog;
    private ImageFileAdapter adapter;
    private Uri imageUri;
    private InvokeParam invokeParam;
    private List<UpdateUserIconBean> photos = new ArrayList<>();
    private File newFile = null;

    private String sprName;
    private int limt;
    private ArrayList<TImage> list;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spare_audit);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        getTakePhoto().onCreate(savedInstanceState);

        sprId = getIntent().getStringExtra("sprId");
        spareId = getIntent().getStringExtra("spareId");
        sprName = getIntent().getStringExtra("sprName");
        initData();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getTakePhoto().onSaveInstanceState(outState);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        configCompress(takePhoto);
        return takePhoto;
    }

    //配置图像压缩相关
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxSize(1024000)
                .create();
        config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, false);
    }

    private void initData() {
        simpleTileView.setTitle("审核");
        tvSpare.setText(sprName);

        rlSpare.setOnClickListener(this);
        buttonThrough.setOnClickListener(this);
        buttonNotThrough.setOnClickListener(this);
        buttonCancel.setOnClickListener(this);
        promptDialog = new PromptDialog(this);
        tvInputTitle.setText("审核意见");
        etInputContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100), AppHelper.emojiFilter});
        etInputContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = s.length();
                tvInputNumber.setText(length + "");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 上传附件图片
        adapter = new ImageFileAdapter(mContext);
        adapter.setOnItemDeleteClickListener(this);
        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = null;
            if (data != null) {
                bundle = data.getExtras();
            }
            if (requestCode == 111) {
                if (!TextUtils.isEmpty(bundle.getString("hardName"))) {
                    tvSpare.setText(bundle.getString("hardName"));
                }
                spareId = bundle.getString("spareId");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.button_through://通过
                spareNext("2");
                break;
            case R.id.button_not_through://不通过
                spareNext("3");
                break;
            case R.id.button_cancel://取消
                finish();
                break;
            case R.id.rl_spare: //选择备件
                startActivityForResult(new Intent(this, SpareSelectActivity.class), 111);
                break;
            default:
                break;
        }
    }

    private void spareNext(String flag) {
        auditSay = etInputContent.getText().toString().trim();
        String filenames = "";
        String attachPath = "";
        String attachSize = "";
        for (int i = 0; i < photos.size(); i++) {
            UpdateUserIconBean photo = photos.get(i);
            if (i == 0) {
                filenames = photo.getName();
                attachPath = photo.getPath();
                attachSize = photo.getSize();
            } else {
                filenames += "," + photo.getName();
                attachPath += "," + photo.getPath();
                attachSize += "," + photo.getSize();
            }
        }

        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {//业主
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {//服务商
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        map.put("attachPath", attachPath);
        map.put("attachSize", attachSize);
        map.put("filenames", filenames);
        map.put("auditSay", auditSay);
        map.put("flag", flag);
        map.put("sprId", sprId);
        map.put("spareId", spareId);
        ServiceRequestManager.getManager().setSpareAudit(this, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                ReturnBean ownerBean = new Gson().fromJson(result, ReturnBean.class);
                if (ownerBean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("操作成功");
                    EventBus.getDefault().post(new SparePageRefreshEvent());
                    finish();
                } else if (ownerBean.getMessage().getCode() == 1008) {
                    showCenterInfoMsg("无权限访问");
                } else if (ownerBean.getMessage().getCode() == 1019) {
                    showCenterInfoMsg("申请的备件无库存");
                } else if (ownerBean.getMessage().getCode() == 1020) {
                    showCenterInfoMsg("备件申请已审核");
                } else {
                    showCenterInfoMsg(ownerBean.getMessage().getMessage());
                }
                break;
            case 999: //上传
                UpdateUserIconBean bean = new Gson().fromJson(result, UpdateUserIconBean.class);
                photos.add(bean);
                for (TImage image : list) {
                    String image2Name = new File(image.getCompressPath()).getName();
                    if (image2Name.equals(bean.getName())) {
                        adapter.addItem(image.getCompressPath());
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    @Override
    public void takeSuccess(TResult result) {
        try {
            list = result.getImages();
            for (TImage it : list) {
                newFile = new File(it.getCompressPath());
                if (newFile.exists()) {
                    UploadManger manger = UploadManger.getManager();
                    if ("1".equals(companyType)) {
                        manger.uploadIcon(mContext, newFile, this, ownerBean.getRows().getCompany().getVersionCode()
                                , ownerBean.getRows().getCompany().getCompanyCode());
                    } else if ("2".equals(companyType)) {
                        manger.uploadIcon(mContext, newFile, this, serviceLoginBean.getRows().getCompany().getVersionCode()
                                , serviceLoginBean.getRows().getCompany().getCompanyCode());
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showCenterInfoMsg(this.getString(R.string.tip_file_is_not_exist));
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        LogUtil.e(TAG + "takeFail：" + result);
    }

    @Override
    public void takeCancel() {
        LogUtil.e(TAG + "takeCancel：");
    }

    @Override
    public void onDeleteClick(int position) {
        adapter.deleteItem(position);
        photos.remove(position);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (position == (adapter.getmList() == null ? 0 : adapter.getmList().size())) { // 获取本地文件
            limt = 10 - (adapter.getCount() - 1);
            if (limt > 0) {
                PromptButton cancle = new PromptButton("取消", null);
                File file = new File(getApplication().getCacheDir(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                imageUri = Uri.fromFile(file);
                LogUtil.e("imageUri " + imageUri.toString());
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("打开相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickMultiple(limt);
                               // showTopWrongMsg("当前还可以选择" + limt + "张图片附件");
                            }
                        }), new PromptButton("拍照", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromCapture(imageUri);
                            }
                        }));
            } else {
                showTopWrongMsg("最多只能选择10张");
            }

        } else {
            // 展示图片
            ArrayList<String> list = new ArrayList<>();
            list.addAll(adapter.getmList());
            PhotoDisplayActivity.OpenActivity(mContext, list, position);
        }
    }
}
